jQuery.noConflict();

// add ability to delete nested records
jQuery(document).ready(function() {
  jQuery("#work_area").find("input[type='checkbox'][spec_num]").change(function(){
    setValueDeleteRecord(this);
  });
});

//  set value
function setValueDeleteRecord(elem) {
  var el = jQuery(elem);
  index = el.attr("spec_num");
  
  if (el.attr("checked") == true) {
    jQuery(jQuery("#work_area").find("input[del_rec]")[index]).val("");
  }
  else {
    jQuery(jQuery("#work_area").find("input[del_rec]")[index]).val("1");
  }
}

// plugin check/uncheck checkboxes (extend jQuery)
// remove to utils file for all !!!!!
jQuery.fn.check = function(mode) {
   // if mode is undefined, use 'on' as default
   var mode = mode || 'on';
   
   return this.each(function() {
     switch(mode) {
       case 'on':
         this.checked = true;
         break;
       case 'off':
         this.checked = false;
         break;
       case 'toggle':
         this.checked = !this.checked;
         break;
     }
   });
 };

//  ApplicationAccounts:new, edit - add a new bundle select to bundles - inserts HTML (select and hidden checkboxes) on click of "Add Bundle". Duplicates HTML of "origin_elem" div
jQuery(document).ready(function() { 
	jQuery("#addElem").click(function(){
    var ppp = jQuery(jQuery("#div_add > #origin_elem")[0]).clone(true);
    ppp.find("input[type='checkbox']").each(function(i) {
      jQuery(this).check('off');
    });
    ppp.find("select").val("").attr("selected", "");
    ppp.find("div").hide();
    ppp.appendTo("#div_add");
 	});
});

//  ApplicationAccounts:new, edit - show variations for selected bundle
function showVariations(which) {
  var all_vars = jQuery(which).parent("div");
  var ar = all_vars.find("div");
  ar.hide();
  all_vars.find("input[type='checkbox']").each(function(i) {
    jQuery(this).check('off');
  });
  
  i = which.selectedIndex;
  if(i==0) 
    return true;
  jQuery(ar[i-1]).show();
}

// ApplicationAccounts:new, edit - bind function to several selects
jQuery(document).ready(function() {
  jQuery("#div_add").find("select").keyup(function(){
    showVariations(this);
  });
  
  jQuery("#div_add").find("select").change(function(){
    showVariations(this);
  });
});

// Add/Remove multiple options (Create/Edit Bundle)
jQuery(function() {  
	jQuery(".select input[type='button']").click(function(){ 
		var arr = jQuery(this).attr("name").split("-");  
		var from = arr[0];  
		var to = arr[1];  
		jQuery("#" + from + " option:selected").each(function(){  
			jQuery("#" + to).append(jQuery(this).clone());  
			jQuery(this).remove();  
		});  
	});  
})